package site.eblog.listener;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.alibaba.fastjson.JSONObject;

public class FileUploadUtil {
	
	@Autowired //UserService userService;
	
	public static Map<String,String> upLoadFile(HttpServletRequest request, CommonsMultipartFile file) {
		//System.out.println(request.getParameter("author"));
				Map<String,String> resMsg = new HashMap<String, String>();
				String upRes = "";
				String picPath = "";
				String fileName = "";
				String type = request.getParameter("type");
				Subject currentUser = SecurityUtils.getSubject();
				String userName = currentUser.getPrincipal().toString();
				String path = request.getSession().getServletContext().getRealPath("assets/manager/upload/" + userName);
				String[] suffixA = file.getOriginalFilename().split("\\.");
				String suffix = suffixA[1];
				fileName = type + "." + suffix;
				picPath = "assets/manager/upload/" + userName + "/" + fileName;
				File targetFile = new File(path, fileName);
				if (!targetFile.exists()) {
					targetFile.mkdirs();
				}
				//保存
				try {
					file.transferTo(targetFile);
					upRes = "true";
					resMsg.put("upRes", upRes);
					resMsg.put("type", type);
					resMsg.put("picPath", picPath);
					return resMsg;
				} catch (Exception e) {
					e.printStackTrace();
					upRes = "false";
					resMsg.put("upRes", upRes);
					return resMsg;
				}
	}
}
